<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="待处理" name="1"></el-tab-pane>
      <el-tab-pane label="已处理" name="3"></el-tab-pane>
    </el-tabs>
    <el-form :inline="true" :model="dataForm" size="mini" label-suffix=":">
      <el-form-item label="教材名称">
        <el-input v-model.trim="dataForm.bookName" style="width: 200px" placeholder="请输入教材名称" clearable
          show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker v-model="createTimeRange" type="daterange" value-format="yyyy-MM-dd" range-separator="至"
          start-placeholder="开始日期" end-placeholder="结束日期" clearable @change="changeDate">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getDataList({ current: 1 })">查询</el-button>
        <el-button @click="resetForm('form')">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="avue-form">
      <el-table ref="mainT" v-loading="dataListLoading" :data="dataList" border tooltip-effect="dark">
        <el-table-column type="index" :index="indexMethod" header-align="center" align="center" label="序号"
          width="80"></el-table-column>
        <el-table-column prop="apply_code" header-align="center" align="center" label="申请编号"></el-table-column>
        <el-table-column prop="book_name" header-align="center" align="center" label="教材名称" show-overflow-tooltip />
        <el-table-column prop="course_name" header-align="center" align="center" label="课程名称"></el-table-column>
        <el-table-column prop="nick_name" header-align="center" align="center" label="发起人"></el-table-column>
        <el-table-column prop="leader_name" header-align="center" align="center" label="组长"></el-table-column>
        <el-table-column header-align="center" align="center" label="申请时间">
          <template slot-scope="scope"> {{ parseTime(scope.row.create_time) }}</template>
        </el-table-column>
        <el-table-column header-align="center" align="center" label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleApplyFor(scope.row.id, scope.row.expert_leader_user_id)">{{
              dataForm.status === 3 ? '查看详情' : '处理' }}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="avue-crud__pagination">
      <el-pagination :current-page="dataForm.current" :page-sizes="[10, 20, 50, 100]" :page-size="dataForm.size"
        :total="total" background layout="total, sizes, prev, pager, next, jumper" @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"></el-pagination>
    </div>
    <el-dialog :visible.sync="dialogHandlerVisible" :destroy-on-close="true">
      <Approve ref="approve" v-if="dialogHandlerVisible" :applyId="applyForId" />
      <span v-if="dataForm.status != 3" slot="footer" class="dialog-footer">
        <el-button @click="dialogRefuseVisible = true">拒 绝</el-button>
        <!-- 只有专家组组长 才有复审通过 -->
        <el-button v-if="isAlike()" type="success" @click="dialogPassVisible = true">复审通过</el-button>
        <el-button type="primary" @click="normalPassClickHandler">通 过</el-button>
      </span>
    </el-dialog>
    <!-- 拒绝弹框 -->
    <el-dialog title="未通过理由" :visible.sync="dialogRefuseVisible">
      <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 999 }" placeholder="请输入审批打回理由（必填）"
        v-model="refuseContent">
      </el-input>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRefuseVisible = false">取 消</el-button>
        <el-button type="primary" @click="refuseHandler">确 认</el-button>
      </span>
    </el-dialog>
    <!-- 普通通过弹框 -->
    <el-dialog :visible.sync="normalDialogPassVisible" width="800px" :before-close="normalCancelHandler">
      <div class="common-color-9">建议</div>
      <el-input class="margin-top-20" type="textarea" :autosize="{ minRows: 4, maxRows: 9 }" :maxlength="100"
        show-word-limit placeholder="请输入审批建议（必填）" v-model="normalPassContent">
      </el-input>
      <!-- 普通通过 院长或者书记才有签名 -->
      <div v-if="roles.includes('admin_yz') || roles.includes('admin_sj')" class="margin-top-20">
        <div class="common-color-9">电子签字</div>
        <div class="esign">
          <div class="esign-box">
            <VueSignaturePad width="100%" height="300px" ref="signaturePad" />
          </div>
        </div>
        <el-button type="warning" @click="normalHandleReset()">清空画板</el-button>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="normalCancelHandler">取 消</el-button>
        <el-button type="primary" @click="normalPassHandler">确 认</el-button>
      </span>
    </el-dialog>
    <!-- 复审通过弹框 专家组组长用 -->
    <el-dialog :visible.sync="dialogPassVisible" width="800px" :before-close="cancelHandler">
      <div class="common-color-9">建议</div>
      <el-input class="margin-top-20" type="textarea" :autosize="{ minRows: 4, maxRows: 9 }" :maxlength="100"
        show-word-limit placeholder="请输入审批建议（必填）" v-model="passContent">
      </el-input>
      <div class="margin-top-20">
        <div class="common-color-9">电子签字</div>
        <div class="esign">
          <div class="esign-box">
            <VueSignaturePad width="100%" height="300px" ref="signaturePad" />
          </div>
        </div>
        <el-button type="warning" @click="handleReset()">清空画板</el-button>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelHandler">取 消</el-button>
        <el-button type="primary" @click="passHandler">确 认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getBookApplyList } from "@/api/bkmanage/application";
import { getAuditing, getAuditExpertLeaderStatus } from "@/api/bkmanage/auditing"
import Approve from "./approve.vue"
export default {
  name: "manage-auditing",
  components: { Approve },
  data() {
    return {
      activeName: '1',  // 默认选中待处理
      dataForm: {
        bookName: "",
        beginDate: "",
        endDate: "",
        // 1待审核；2审核中；3已完成
        status: 1,
        current: 1,
        size: 20,
      },
      total: 0, // 数据总条数
      // 查询日期
      createTimeRange: "",
      dataList: [], // 审核列表
      dataListLoading: false,
      dialogHandlerVisible: false,  // 处理申请弹框是否显示
      form: {
        bookId: "", // 教材id
        academyUsedName: "", // 学院
        semester: "", //学期
        applyReason: "",
        type: "",
      },
      applyForId: '',  // 申请id
      dialogRefuseVisible: false,  // 拒绝申请弹框是否显示
      refuseContent: '', // 拒绝理由

      dialogPassVisible: false,  // 复审通过弹框是否显示
      passContent: '', // 复审通过时的审批建议 
      normalDialogPassVisible: false,  // 普通通过弹框是否显示
      normalPassContent: '', // 普通通过时的审批建议
      /** 签字画板参数 */
      imgSrc: '',  // base64地址
      userId: '',  // 用户id
      roles: [], // 用户角色
    };
  },
  created() {
    // store 中取出当前登录的userid 和 roles
    this.userId = this.$store.state.user.id;
    this.roles = this.$store.state.user.roles;
    this.getDataList();
  },
  methods: {
    // 获取审批列表
    getDataList(params) {
      this.dataListLoading = true
      getBookApplyList(Object.assign(this.dataForm, params, { searchType: 2 })).then((res) => {
        this.dataList = res?.rows;
        this.total = res?.total;
      }).finally(() => {
        this.dataListLoading = false;
      });

    },
    // 序号处理
    indexMethod(index) {
      return index + 1;
    },
    // 开始、结束日期
    changeDate(e) {
      if (e.length > 0) {
        this.dataForm.beginDate = e[0]
        this.dataForm.endDate = e[1]
      }
    },
    // 重置表单
    resetForm() {
      this.dataForm = {
        bookName: "",
        beginDate: "",
        endDate: "",
        // 1待审核；2审核中；3已完成
        status: this.dataForm.status,
        current: 1,
        size: 20,
      };
      this.getDataList()
    },
    // 处理申请
    handleApplyFor(id, leader_user_id) {
      // 专家组长id
      this.leaderUserId = leader_user_id
      if (!id) return
      this.applyForId = id
      this.dialogHandlerVisible = true;
    },
    // 当前登录用户是否是专家组组长
    isAlike() {
      return this.userId === this.leaderUserId ? true : false
    },
    // 每页数
    sizeChangeHandle(val) {
      this.getDataList({ current: 1, size: val });
    },
    // 当前页
    currentChangeHandle(val) {
      this.getDataList({ current: val });
    },
    // 点击切换 待处理、已处理
    handleClick(e) {
      if (!e) return
      if (e.index === '0') {
        this.dataForm.status = 1
        this.getDataList({ current: 1, size: 20 });
      }
      if (e.index === '1') {
        this.dataForm.status = 3
        this.getDataList({ current: 1, size: 20 });
      }


    },
    // 拒绝处理
    refuseHandler() {
      if (!this.refuseContent) return this.$message.error('请输入审批打回理由')
      const data = {
        applyId: this.applyForId,
        opinion: this.refuseContent,
        signature: '',
        status: 2  // 1通过；2驳回
      }
      getAuditing(data).then(() => {
        this.$message.success('操作成功')
        // 关闭拒绝弹框并清空输入框的值
        this.dialogRefuseVisible = false
        this.refuseContent = ''
        // 刷新列表和 详情
        this.refreshListAndDetail()
      })
    },
    // 点击普通通过按钮，院长书记需要签字，其他不需要签字，需要填写建议，秘书不填写建议不签字 老师：admin_xyls  学院秘书：admin_xyms 学院院长：admin_yz 学院书记：admin_sj
    normalPassClickHandler() {
      // 秘书不填写建议不签字
      if (this.roles.includes('admin_xyms')) {
        this.$confirm('确定审批通过吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const data = {
            applyId: this.applyForId,
            opinion: '',
            signature: '',
            status: 1  // 1通过；2驳回
          }
          getAuditing(data).then(() => {
            this.successHandler()
          })
        }).catch(() => { });
      } else {
        this.normalDialogPassVisible = true
      }
    },
    // 普通通过确认按钮
    async normalPassHandler() {
      if (!this.normalPassContent) return this.$message.error('请输入审批建议')
      if (this.roles.includes('admin_yz') || this.roles.includes('admin_sj')) {
        await this.handleGenerate()
        if (!this.imgSrc) return this.$message.error('请输入电子签名')
      }
      const data = {
        applyId: this.applyForId,
        opinion: this.normalPassContent,
        signature: this.imgSrc,
        status: 1  // 1通过；2驳回
      }
      getAuditing(data).then(() => {
        this.normalSuccessHandler()
      })
    },
    normalSuccessHandler() {
      this.$message.success('操作成功')
      // 关闭弹框并清空输入框的值
      this.normalDialogPassVisible = false
      this.normalPassContent = ''
      this.imgSrc = ''
      this.handleReset()
      // 关闭详情弹框
      this.dialogHandlerVisible = false
      // 刷新列表和 详情
      this.refreshListAndDetail()
    },
    // 普通通过 弹框 取消按钮
    normalCancelHandler() {
      this.$confirm('确定取消吗，内容将不做保存？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.normalDialogPassVisible = false
        this.normalPassContent = ''
        this.imgSrc = ''
        this.handleReset()
      }).catch(() => { });

    },

    // 复审确认通过按钮
    async passHandler() {
      if (!this.passContent) return this.$message.error('请输入审批建议')
      await this.handleGenerate()
      if (!this.imgSrc) return this.$message.error('请输入电子签名')
      const data = {
        applyId: this.applyForId,
        opinion: this.passContent,
        signature: this.imgSrc,
        status: 1  // 1通过；2驳回
      }
      // 只有专家组组长 才有复审通过
      if (this.isAlike()) {
        getAuditExpertLeaderStatus(data).then(() => {
          this.successHandler()
        })
      } else {
        getAuditing(data).then(() => {
          this.successHandler()
        })
      }

    },
    // 复审通过 弹框 取消按钮
    cancelHandler() {
      this.$confirm('确定取消吗，内容将不做保存？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogPassVisible = false
        this.passContent = ''
        this.imgSrc = ''
        this.handleReset()
      }).catch(() => { });

    },
    successHandler() {
      this.$message.success('操作成功')
      // 关闭弹框并清空输入框的值
      this.dialogPassVisible = false
      this.passContent = ''
      this.imgSrc = ''
      this.handleReset()
      // 关闭详情弹框
      this.dialogHandlerVisible = false
      // 刷新列表和 详情
      this.refreshListAndDetail()
    },

    // 刷新列表和 详情
    refreshListAndDetail() {
      this.$refs.approve.getBookInfo()
      this.getDataList()
    },
    // 普通、复审通过时 保存签名
    handleGenerate() {
      const { data } = this.$refs.signaturePad.saveSignature();
      this.imgSrc = data;
    },
    // 清除画板
    handleReset() {
      this.$refs.signaturePad.clearSignature();
    },

  },
};
</script>
<style lang="scss" scoped>
.esign {
  max-width: 1000px;
  margin: auto;
  padding: 20px 0;
}

.esign-box {
  border: 1px solid #C0C4CC;
}
</style>
